package com.sxc.OnlineStore.user.servlet;

import com.sxc.OnlineStore.user.dao.UserIm;
import com.sxc.OnlineStore.user.service.UserConfirmService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/LoginServlet")
/*@WebServlet(name = "LoginServlet", urlPatterns = "/LoginServlet")*/
public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置编码
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        //得到前端传过来的值
        String user_Name = request.getParameter("user_Name");
        String user_PW = request.getParameter("user_PW");

        UserConfirmService ucs = new UserConfirmService();//实例化服务层

        PrintWriter out = response.getWriter();//定义输出到jsp的对象

        //传值调用函数确认账号密码是否正确
        boolean userStatus = ucs.confirmUser(user_Name,user_PW);
<<<<<<< HEAD
        if (userStatus){
            //用户名和密码正确

=======
        //用户名和密码正确
        if (userStatus){
>>>>>>> 还没有实现在servlet中获取sessiond
            //使用request对象的getSession()获取session，如果session不存在则创建一个
            // 用于传userPK，以及userName
            HttpSession session = request.getSession();

            UserIm userIm = new UserIm();
            int userPK = userIm.GetUserPK(user_Name);
<<<<<<< HEAD
=======
            //登录成功创建user的session会话
>>>>>>> 还没有实现在servlet中获取sessiond
            session.setAttribute("userPK",userPK);

            session.setAttribute("userName",user_Name);
            request.getRequestDispatcher("home.jsp").forward(request,response);
        }else{
            //密码错误重定向到登录界面更具交互性虽然还是挺lou滴~
            out.write("<script>alert(\"密码错误了呀~~请重新输入哟\");location.replace(\"user_login.jsp\");</script></script>");
            System.out.print("**************************erro重新登录**************************");
            //request.getRequestDispatcher("user_login.jsp").forward(request,response);
        }

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request,response);
    }
}
